function [Ypred] = svm(data, label, C, ktype)
% SVM function [Ypred] = svm(data, label, C, ktype)
%       classifies the unlabeled instances in data according
%       to the labeled ones using support vector machine
%       
%       label contains the class for first part of data
%       and Ypred contains the results for the rest
%
%       ktype == 1 linear
%                     2 polynomial 
%                     3 rbf
%
%       version 0.1, 04/06/2014
%       Suqi Liu

X = double(data); %size n, both labeled and unlabeled data
Y = double(label); %size l < n, labels

l = size(Y,1);
n = size(X,1);

Xtr = X(1:l,:);
Xts = X(l+1:n,:);

dim = 2;
sigma = 1;

if (ktype ==1)
    K = Xtr*Xtr';
end
if (ktype == 2)
    K = (1+Xtr*Xtr').^dim;
end
if (ktype == 3)
    Ktmp = Xtr*Xtr';
    xs = diag(Ktmp);
    K = exp((2*Ktmp - repmat(xs,1,l) - repmat(xs',l,1))/(2*sigma));
    clear Ktmp;
end

K = K/max(max(K));

Q = (Y*Y').*K;
clear K;

cvx_begin
cvx_solver sedumi
    variable a(l) nonnegative
    minimize (a'*Q*a - 2*ones(1,l)*a)
    subject to
%        Y'*a == 0
        a <= C
cvx_end

%b = Y(1) - Q(1,:)*a/Y(1);

clear Q;

if (ktype ==1)
    T = Xts*Xtr';
end
if (ktype == 2)
    T = (1+Xts*Xtr').^dim;
end
if (ktype == 3)
    Ttmp = Xts*Xtr';
    ts = sum(Xts.*Xts,2);
    T = exp((2*Ttmp - repmat(ts,1,l) - repmat(xs',n-l,1))/(2*sigma));
    clear Ttmp;
    clear ts;
end

Ypred = int8(sign(T*(Y.*a)));
end
